package web

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"testPaper/common"
	"testPaper/model"
	"testPaper/response"
)

// QueryNewTopic 获取题目
func QueryNewTopic(c *gin.Context) {
	DB := common.GetDB()
	subject := c.PostForm("subject")
	paperId := c.PostForm("paperId")
	types := c.PostForm("type")
	caseId := c.PostForm("caseId")
	pageSize, _ := strconv.Atoi(c.PostForm("pageSize"))
	pageIndex, _ := strconv.Atoi(c.PostForm("pageIndex"))

	switch {
	case pageSize >= 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	if pageIndex <= 0 {
		pageIndex = 1
	}

	if CaseExits(DB, paperId) {
		newTopic := make([]model.NewTopic, 0)
		var total int
		if subject != "" {
			DB.Where("paper_id = ? And subject LIKE ? And type = ? And case_id = ?", paperId, "%"+subject+"%", types, caseId).
				Limit(pageSize).
				Offset((pageIndex - 1) * pageSize).
				Find(&newTopic).Offset(-1).
				Limit(-1).Count(&total)
			response.Reponse(c, http.StatusOK, 200, gin.H{
				"data":     newTopic,
				"total":    total,
				"page":     pageIndex,
				"pageSize": pageSize,
			}, "获取成功")
			return
		} else {
			DB.Where("paper_id = ? And type = ? And case_id = ?", paperId, types, caseId).
				Limit(pageSize).Offset((pageIndex - 1) * pageSize).
				Find(&newTopic).Offset(-1).
				Limit(-1).
				Count(&total)
			response.Reponse(c, http.StatusOK, 200, gin.H{
				"data":     newTopic,
				"total":    total,
				"page":     pageIndex,
				"pageSize": pageSize,
			}, "获取成功")
			return
		}
		return
	} else {
		response.Reponse(c, http.StatusOK, 422, nil, "传入的试卷Id不存在")
		return
	}
}
